package cn.wolfcode.web.controller;

import cn.wolfcode.service.IUserService;
import cn.wolfcode.util.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

// 用户控制器(控制登陆和注销)
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    // 登陆验证
    @RequestMapping("/login")
    @ResponseBody // 只响应结果不找视图
    public JsonResult login(String username, String password , HttpServletRequest request) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //获取登录的用户主体对象
            Subject subject = SecurityUtils.getSubject();
            //登陆
            subject.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e){
            e.printStackTrace();
            return new JsonResult(false , "账号不存在");
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return new JsonResult(false , "密码错误");
        } catch (DisabledAccountException e){
            e.printStackTrace();
            return new JsonResult(false , "账号已被冻结");
        } catch (Exception e) {
            e.printStackTrace();
            // 获取异常信息然后告知用户
            return new JsonResult(false , e.getMessage());
        }
    }

    @RequestMapping("/state")
    public String state(Long id ,Integer currentPage) {
        //传给业务层,修改状态
        userService.state(id);
        // 刷新页面
        return "redirect:/employee/list.do?currentPage=" + currentPage;
    }


   /* // 注销
    @RequestMapping("/logout")
    public String Logout() {
        // 删除session
        UserContext.logoutCurrentUser();
        // 重定向回登陆界面
        return "redirect:/login.html";
    }*/
}
